const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const CompressionWebpackPlugin = require("compression-webpack-plugin");

module.exports = function(env = {}, args) {

	const isProduction = env['production']
	const plugins = []
	if(isProduction) {
		plugins.push(new BundleAnalyzerPlugin())
	}else {
		plugins.push(new webpack.HotModuleReplacementPlugin())
	}

	return  {
		mode: isProduction ? 'production' : 'development',
		context: path.resolve(__dirname, '../'),
		entry: {
			app: './src/index.js'
		},
		output: {
			filename: '[name].bundle.js',
			path: path.resolve(__dirname, '../dist')
		},
		module: {
			rules: [
				{
					test: /\.(js|jsx)$/,
					loader: 'babel-loader',
					exclude: /node_modules/
				},
				{
					test: /\.css/,
					include: /src/,
					use: ['css-hot-loader', MiniCssExtractPlugin.loader, 'css-loader?modules&localIdentName=[name]__[local]-[hash:base64:5]']
				},
				{
					test: /\.css/,
					exclude: /src/,
					use: [MiniCssExtractPlugin.loader, 'css-loader']
				},
				{
					test: /\.less$/,
					exclude: /node_modules/,
					use: ['css-hot-loader', MiniCssExtractPlugin.loader, 'css-loader?modules&localIdentName=[name]__[local]-[hash:base64:5]', 'less-loader']
				},
				{
					test: /\.(jpg|jpeg|png|gif)$/,
					use: [
						{
							loader: 'url-loader',
							options: {
								limit: 8192,    // 小于8k的图片自动转成base64格式，并且不会存在实体图片
								outputPath: 'images/',  // 图片打包后存放的目录
								publicPath: '/images/'
							}
						}
					]
				},
				{
					test: /\.(eot|ttf|woff|svg)$/,
					use: 'file-loader'
				}
			]
		},
		resolve: {
			extensions: ['.js', '.jsx', '.json', 'less'],
			// 配置别名
			alias: {
				utils: path.resolve(__dirname, '../src/utils'),
				widget: path.resolve(__dirname, '../widget'),
				pages: path.resolve(__dirname, '../src/pages'),
				config:  path.resolve(__dirname, '../src/config')
			}
		},
		plugins: [
			...plugins,
			// 清除dist目录的内容
			new CleanWebpackPlugin([path.resolve(__dirname, '../dist')], {
				root: path.resolve(__dirname, '../')
			}),
			// 分离css插件
			new MiniCssExtractPlugin({
				filename: 'css/[name].css'   // 指定打包后的css
			}),
			// lodash按需加载
			new LodashModuleReplacementPlugin(),

			// 以后再开启，需要修改目录，不然设置了代理全部转接到了另外一台服务器
			new webpack.DllReferencePlugin({
			  // 描述 react 动态链接库的文件内容
			  manifest: require(path.resolve(__dirname, '../dll/site/vendor-manifest.json')),
			}),
			new webpack.ContextReplacementPlugin(
				/moment[/\\]locale$/,
				/zh-cn/,
			),
			new OptimizeCSSAssetsPlugin({
				// 对css进行压缩
				assetNameRegExp: /\.css$/g,
				cssProcessor: require('cssnano'),
				// cssProcessorOptions: cssnanoOptions,
				cssProcessorPluginOptions: {
					preset: ['default', {
								discardComments: {
										removeAll: true,
								},
								normalizeUnicode: false
						}]
				},
				canPrint: true
			}),
			new CompressionWebpackPlugin({
				// 将代码使用gzip压缩
				filename: '[path].gz[query]',
				algorithm: 'gzip',
				test: new RegExp('\\.(js|css)$'),
				threshold: 10240,
				minRatio: 0.8
			}),
			new HtmlWebpackPlugin({
				template: path.resolve(__dirname, '../src/assets/index.html')
			}),
		],
		devtool: isProduction ? '' : 'cheap-module-eval-source-map',
		devServer: {
			contentBase: 'dist',
			host: 'localhost',
			port: "3008",
			open: true,
			hot: true,
			overlay: true,
			proxy: {
		  		'/': {
		  			target: 'http://localhost:8081',
		  			changeOrigin: true
		  		}
	  		}
		},
		optimization: {
			runtimeChunk: 'single',
			splitChunks: {
			  chunks: 'all',  //默认只作用于异步模块，为`all`时对所有模块生效,`initial`对同步模块有效
			  minSize: 30000,  //合并前模块文件的体积
			  minChunks: 1,   //最少被引用次数
			  cacheGroups: { //定义规则
					vendors: {
						test: /node_modules/,
						chunks: 'all',
					  minChunks:1,//敲黑板
					  priority: -10,//优先级更高
					  name: 'vendor'
					},
					styles: {
							name: 'style',
							test: /\.css$/,
							chunks: 'all',
							enforce: true
					},
					antd: {
						test: /antd/,
						minChunks: 1,
						priority: -9,
						name: 'antd'
					},
					lodash: {
						test: /lodash/,
						minChunks: 1,
						priority: -8,
						name: 'lodash'
					},
					echart: {
						test: /echart/,
						minChunks: 1,
						priority: -7,
						name: 'echart'
					}
		  	}
			}
		},
		stats: {
			modules: false
		}
	}
}